<template>
  <Main :type="'form'">
    <Title :title="pageName" />
    <el-row>
      <el-col :span="24">
        <el-form ref="form" label-width="150px" :model="form" :rules="form">
          <el-form-item
            label="自提点名称"
            prop="name"
            :rules="{
              required: true,
              message: '请输入自提点名称',
              trigger: 'blur'
            }"
          >
            <el-input
              v-model="form.name"
              class="form-input"
              placeholder="请输入自提点名称"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="自提点管理员账号"
            prop="username"
            :rules="{
              required: true,
              message: '请输入自提点管理员账号',
              trigger: 'blur'
            }"
          >
            <el-input
              v-model="form.username"
              class="form-input"
              placeholder="请输入自提点管理员账号"
              size="medium"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="管理员姓名"
            prop="name"
            :rules="{ required: true, message: '请输入名称', trigger: 'blur' }"
          >
            <el-input
              v-model="form.truename"
              class="form-input"
              placeholder="请输入模板名称"
              size="medium"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="联系电话"
            prop="phone"
            :rules="{
              required: true,
              message: '请输入联系电话',
              trigger: 'blur'
            }"
          >
            <el-input
              v-model="form.phone"
              class="form-input"
              size="medium"
              :maxlength="11"
              onkeyup='value=value.replace(/\D/g,"")'
              onpaste='value=value.replace(/\D/g,"")'
              oncontextmenu='value=value.replace(/\D/g,"")'
              placeholder="请输入联系电话"
              @change="inputTagPhone"
            ></el-input>
          </el-form-item>
          <el-form-item
            prop=""
            :rules="{
              required: true,
              message: '请选择营业时间',
              trigger: 'blur'
            }"
            label="营业时间"
            class="interval"
          >
            <el-time-picker
              v-model="valTime"
              is-range
              size="small"
              value-format="HH:mm"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"
            >
            </el-time-picker>
            <el-button
              size="small"
              :disabled="timeArr.length >= 3"
              @click="addTime"
              >新增时间段</el-button
            >
            &nbsp;&nbsp; <span style="color:#909399">最多可添加三组</span>
          </el-form-item>
          <el-form-item v-if="timeArr.length > 0">
            <div class="timeC">
              <p
                v-for="(item, index) in timeArr"
                :key="index"
                class="time-chlid"
              >
                {{ item.start }}-{{ item.end }}
                <i class="el-icon-delete time-del" @click="timeDel(index)"></i>
              </p>
            </div>
          </el-form-item>
          <el-form-item>
            <el-checkbox-group v-model="form.open_week">
              <el-checkbox label="1">周一</el-checkbox>
              <el-checkbox label="2">周二</el-checkbox>
              <el-checkbox label="3">周三</el-checkbox>
              <el-checkbox label="4">周四</el-checkbox>
              <el-checkbox label="5">周五</el-checkbox>
              <el-checkbox label="6">周六</el-checkbox>
              <el-checkbox label="7">周日</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item
            label="自提点地址"
            prop="position"
            :rules="{ required: true, message: '请选择地区', trigger: 'blur' }"
          >
            <el-cascader
              v-model="form.position"
              :options="options"
              :props="defaultProps"
              class="form-input"
              change-on-select
              @change="cascaderTag"
            ></el-cascader>
          </el-form-item>

          <el-form-item
            label="详细地址"
            prop="address"
            :rules="{
              required: true,
              message: '请输入详细地址',
              trigger: 'blur'
            }"
          >
            <el-input
              v-model="form.address"
              placeholder="请输入内容"
              style="width:50%;"
              size="medium"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="searchTag"
              ></el-button>
            </el-input>
          </el-form-item>
          <el-form-item
            label="选取地址"
            prop="longitude"
            :rules="{ required: true, message: '请选取地址', trigger: 'blur' }"
          >
            <GDmap
              :type="'Marker'"
              style="margin-top:20px;"
              :datas="{ search: searchs }"
              @retunrData="retunrData"
            />
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <Footer>
      <el-button plain @click="$emit('out')">取 消</el-button>
      <el-button type="primary" @click="submit">保 存</el-button>
    </Footer>
  </Main>
</template>
<script>
import { SETYOURSELFPOINT } from "../../service";
import { THREELEVELLINKAGE } from "@/service/public";

export default {
  components: {
    GDmap: () => import("publicCom/GDmap")
  },
  props: {
    dataMsg: {
      default: () => {},
      type: Object
    }
  },
  data() {
    return {
      pageName: "新建自提点",
      form: {
        name: "",
        username: "",
        truename: "",
        phone: "",
        open_time: "",
        open_week: [],
        position: [],
        positions: "",
        address: "",
        longitude: "",
        latitude: ""
      },
      searchs: "",
      addressJson: {},
      options: [],
      defaultProps: {
        value: "id",
        children: "children",
        label: "name"
      },
      valTime: "",
      timeArr: [],
      point_id: ""
    };
  },
  created() {
    let json = JSON.stringify(this.dataMsg);
    if (json !== "{}") {
      this.pageName = "编辑自提点";
      this.form.name = this.dataMsg.name;
      this.form.username = this.dataMsg.username;
      this.form.truename = this.dataMsg.truename;
      this.form.phone = JSON.parse(this.dataMsg.phone);
      this.form.longitude = this.dataMsg.latitude;
      this.form.latitude = this.dataMsg.latitude;
      this.form.open_week = this.dataMsg.open_week;
      this.form.address = this.dataMsg.address;
      this.searchs = this.dataMsg.address;
      this.form.positions = this.dataMsg.position;
      this.form.position[0] = this.dataMsg.province;
      this.form.position[1] = this.dataMsg.city;
      this.form.position[2] = this.dataMsg.area;
      this.point_id = this.dataMsg.point_id;
      let arr = this.dataMsg.open_time.split(",");
      arr.forEach(ele => {
        ele = ele.split("-");
        this.timeArr.push({ start: ele[0], end: ele[1] });
      });
    } else {
      this.pageName = "新建自提点";
    }
    this.getAddress();
  },
  methods: {
    async getAddress(obj) {
      await THREELEVELLINKAGE(obj).then(res => {
        let { code, data, msg } = res;
        if (code === 200) {
          this.options = data;
          if (this.pageName === "编辑自提点") {
            this.cascaderTag(this.form.position, "edit");
          }
        } else {
          this.$message.error(msg);
        }
      });
    },
    cascaderTag(e, type) {
      let oneName, twoName, threeName;
      if (e[0]) {
        this.options.forEach(ele => {
          if (ele.id === e[0]) {
            oneName = ele.name;
          }
          if (e[1]) {
            ele.children.forEach(eles => {
              if (eles.id === e[1]) {
                twoName = eles.name;
              }
              if (e[2]) {
                eles.children.forEach(eless => {
                  if (eless.id === e[2]) {
                    threeName = eless.name;
                  }
                });
              }
            });
          }
        });
      }

      this.addressJson = { oneName, twoName, threeName };
      this.searchs = "";
      if (type === "edit") {
        this.searchTag();
      } else {
        this.form.address = "";
      }
    },
    searchTag() {
      this.form.longitude = "";
      this.form.latitude = "";
      this.addressJson.oneName
        ? (this.searchs = this.addressJson.oneName)
        : this.$message.error("选择地区后才可搜索");
      if (this.addressJson.twoName) this.searchs += this.addressJson.twoName;
      if (this.addressJson.threeName)
        this.searchs += this.addressJson.threeName;
      this.form.positions = this.searchs;
      this.searchs += this.form.address;
    },
    retunrData(e) {
      if (e) {
        // this.form.address = e.address
        this.form.longitude = e.lng;
        this.form.latitude = e.lat;
      }
    },
    addTime() {
      if (this.valTime) {
        if (this.timeArr.length > 0) {
          let v = this.valTime[0].replace(/:/g, "");
          let t = this.timeArr[length - 1].end.replace(/:/g, "");
          if (parseInt(v) < parseInt(t)) {
            this.$message.error("新添加时间段不能早于已添加时间段内");
            return;
          }
        }
        this.timeArr.push({ start: this.valTime[0], end: this.valTime[1] });
      } else {
        this.$message.error("请选择时间段");
      }
      this.valTime = "";
    },
    timeDel(i) {
      this.timeArr.splice(i, 1);
    },
    inputTagPhone(e) {
      this.form.phone = e;
    },
    async submit() {
      await this.$refs["form"].validate(valid => {
        if (valid) {
          let openTime = [];
          this.timeArr.forEach(ele => {
            openTime.push(ele.start + "-" + ele.end);
          });
          SETYOURSELFPOINT({
            flag: "save",
            name: this.form.name,
            username: this.form.username,
            truename: this.form.truename,
            phone: this.form.phone,
            open_time: openTime.join(","),
            open_week: this.form.open_week.join(","),
            position: this.form.positions,
            address: this.form.address,
            longitude: this.form.longitude,
            latitude: this.form.latitude,
            point_id: this.point_id
          }).then(res => {
            let { code, msg } = res;
            if (code === 200) {
              this.$emit("out");
            }
            this.$message({
              message: msg,
              type: code === 200 ? "success" : "error"
            });
          });
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.timeC {
  width: 80%;
  display: flex;
  .time-chlid {
    width: 130px;
    height: 40px;
    text-align: center;
    color: #fff;
    background: #c0c4cc;
    position: relative;
    margin: 0 10px 10px 0;
    &:hover .time-del {
      display: inline-block;
    }
    .time-del {
      position: absolute;
      top: 3px;
      right: 3px;
      color: #f56c6c;
      cursor: pointer;
      display: none;
    }
  }
}
</style>
